<?php

namespace app\admin\controller\user;

use app\admin\controller\Projects;
use app\common\controller\Backend;
use app\common\library\Auth;
use Exception;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\db\exception\BindParamException;
use think\exception\PDOException;
use fast\Random;
use think\Db;
use think\exception\ValidateException;


/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where('username<>"admin"')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 清空测评记录
     * @return void
     */
    public function clear($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $result = false;
        Db::startTrans();
        try {
            //删除测评记录表
            Db::name('test_zym_answer')->where(['user_id'=>$ids])->delete();
            Db::name('test_mbti_answer')->where(['user_id'=>$ids])->delete();
            Db::name('test_hld_answer')->where(['user_id'=>$ids])->delete();
            Db::name('test_dyzn_answer')->where(['user_id'=>$ids])->delete();
            //同步删除会员的可信度
            $params['reliability'] = 0;
            $params['reliability_text'] = '';
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        error_reporting(E_ALL);
        ini_set("memory_limit","2048M");
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
        $fieldArr['学籍号'] = 'username';
        $fieldArr['姓名'] = 'nickname';
        $fieldArr['性别'] = 'gender';
        $fieldArr['年级'] = 'grade';
        $fieldArr['班级'] = 'classed';
//        $table = $this->model->getQuery()->getTable();
//        $database = \think\Config::get('database.database');
//        $fieldArr = [];
//        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
//        foreach ($list as $k => $v) {
//            if ($importHeadType == 'comment') {
//                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
//                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
//            } else {
//                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
//            }
//        }
        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = trim($v);
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
//        halt($insert);
        $idcard_str = '';
        $duplicate_rows = []; // 重复数据（行）（比较数据库中数据）
        $insert_data = [];
        foreach ($insert as $key => $v)
        {
            if(!empty($v['username'])){
                // 查重
                $dup_where = [
                    'username' => $v['username'],
                ];
                if ($this->model->where($dup_where)->count()) {
                    $duplicate_rows[] = $insert[$key];
                    continue;
                }
                $salt = Random::alnum();
                $gender = '';
                if($v['gender']=='男'){
                    $gender = 1;
                }
                if($v['gender']=='女'){
                    $gender = 0;
                }
                $insert[$key]['gender'] = $gender;
                $insert[$key]['group_id'] = 1;
                $insert[$key]['jointime'] = time();
                $insert[$key]['salt'] = $salt;
                $insert[$key]['password'] = $this->auth->getEncryptPassword('123456', $salt);
                $insert[$key]['avatar'] = '/assets/img/avatar.png';
                $insert[$key]['status'] = 'normal';
                $insert[$key]['email'] = $v['username'].'@163.com';
                $insert_data[] = $insert[$key];
            }else{
                unset($insert[$key]);
            }
        }
        try {
            $this->model->saveAll($insert_data);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        if(!empty($duplicate_rows) ){
            $msg = '导入成功,<br/>';
            if (!empty($duplicate_rows)) {
                $msg .= '以下数据已存在，没有导入:<br />';
                foreach ($duplicate_rows as $ritem) {
                    $msg .= '学号:'.$ritem['username'] . ',姓名:' . $ritem['nickname'] . '<br />';
                }
            }
            $this->success($msg,'',[],15);
        }else{
            $this->success('导入成功');
        }
    }

    /**
     * 批量生成打包下载
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function batch()
    {
        //获取需要下载哪个用户的资源
        $ids = $this->request->get("ids");
        try {
            //先生成word,然后再打包下载
            foreach (explode(',',$ids) as $v) {
                $project = new Projects();
                $project->generate($v);
            }


            $datas = Db::name('batch_report')->whereTime('createtime','today')->where(['user_id'=>['in',$ids]])->select();
            //获取到数据表中某用户对应的数据集合，表中存储的是文件路径
            $arr = [];
            foreach ($datas as $key => $value) {
                array_push($arr, '/'.$value['url']);
            }
            // 压缩多个文件
            //创建压缩包存放目录
            $path = "/uploads/".date('Y-m-d')."zip/";
            if (!file_exists($path)) {
                mkdir(iconv("UTF-8", "GBK", $path), 0777, true);
            }
            $zip = new \ZipArchive();
            $zip_name = $path . '/' .date('Ymd') . date('His') . '批量下载.zip';
            $res = $zip->open($zip_name, \ZipArchive::CREATE); //打开压缩包
            if ($res === true) {
                //循环文件添加到创建好的压缩包中
                foreach ($arr as $file) {
                    $path_url = '.' . $file;
                    $handle = fopen($path_url, 'rb');  //打开文件目录对应的文件
                    $zip->addFile($path_url, basename($file)); //向压缩包中添加文件
                    fclose($handle);  //关闭文件
                }
            }
            $zip->close(); //关闭压缩包
            if (!file_exists($zip_name)) {
                exit("无法找到文件"); //即使创建，仍有可能失败
            }
            //打包下载zip
            header("Cache-Control:max-age=0");
            header("Content-Description: File Transfer");
            header("Content-disposition: attachment; filename=".basename($zip_name));//文件名
            header("Content-Type:application/zip"); //格式为zip
            header("Content-Transfer-Encoding:binary"); //这是二进制文件
            header("Content-Length:".filesize($zip_name)); //文件大小
            @readfile($zip_name);

        }catch (\think\Exception $exception) {
            $this -> error($exception -> getMessage());
        }

        die('完成');
    }
}